package com.foreknow.elm.service.impl;

import com.foreknow.elm.dao.CartDao;
import com.foreknow.elm.dao.OrderdetailetDao;
import com.foreknow.elm.dao.OrdersDao;
import com.foreknow.elm.dao.impl.CartDaoImpl;
import com.foreknow.elm.dao.impl.OrderdetailetDaoImpl;
import com.foreknow.elm.dao.impl.OrdersDaoImpl;
import com.foreknow.elm.po.Cart;
import com.foreknow.elm.po.Orderdetailet;
import com.foreknow.elm.po.Orders;
import com.foreknow.elm.service.OrdersService;
import com.foreknow.elm.util.DBUtil;

import java.util.ArrayList;
import java.util.List;

public class OrdersServiceImpl implements OrdersService {
    private OrdersDao dao = new OrdersDaoImpl();
    private CartDao cdao=new CartDaoImpl();
    private OrderdetailetDao odao = new OrderdetailetDaoImpl();
    @Override
    public Integer createOrders(Orders orders) {
        int orderId=0;
        try {
            DBUtil.beginTransaction();
            orderId = dao.createOrders(orders);
            List<Cart> list = cdao.listCart(orders.getUserId(), orders.getBusinessId());
            Orderdetailet orderdetailet = new Orderdetailet();
            List<Orderdetailet> orderdetailets = new ArrayList<>();
            for (Cart cart : list) {
                orderdetailet.setOrderId(orderId);
                orderdetailet.setFoodId(cart.getFoodId());
                orderdetailet.setQuantity(cart.getQuantity());
                orderdetailets.add(orderdetailet);
            }
            odao.addOrderDetail(orderdetailets);
            cdao.removeCart(orders.getUserId(),orders.getBusinessId());
            DBUtil.commitTransaction();
        } catch (Exception e) {
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
        return orderId;
    }

    @Override
    public Orders getOrdersById(int orderId) {
        Orders orders = new Orders();
        try {
            orders = dao.getOrdersById(orderId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return orders;
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        List<Orders> list = new ArrayList<>();
        try {
            list = dao.listOrdersByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
